/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import database from './DatabaseUtils'
import CommonEvent from "@ohos.commonEventManager"
import SPLogger from '../utils/SPLogger'
import { dateFormat } from '../utils/TimeUtils'
import { ReportItem } from '../entity/LocalConfigEntity'
import { sql_t_general_info, sql_t_user_info, sql_t_perform_info, sql_t_FrameRate_info, dbName,
  sql_t_gpu_counter_info } from '../constant/ConstantSQL';
import { AppFileRealDir } from '../constant/ConstantsPath'
import { DaoConfig } from "../db/DaoConfig"
import { DbUtils } from "../utils/DbUtils"
import { DbCallBackImp } from "../db/QueryCallBackImp"
import relationalStore from '@ohos.data.relationalStore'
import data from '@ohos.telephony.data'


const TAG = "LocalRepository"


export function initDb(): void {
    const myMap = new Map()
    myMap.set("t_general_info", sql_t_general_info)
    myMap.set("t_user_info", sql_t_user_info)
    myMap.set("t_perform_info", sql_t_perform_info)
    myMap.set("t_FrameRate_info", sql_t_FrameRate_info)

    let config = new DaoConfig()
    config.setDbName(dbName)
    let db = new DbUtils(config)
    db.setCallback(new DbCallBackImp())
    db.execCreate(myMap)
    refreshReportListDb()
    refreshReportPerfDb()
    refreshReportFPSDb()
 }

 export async function refreshReportPerfDb() {
    database.queryPerformInfo().then(data => {
        data.sort(function(a,b) {
            return Number(b.startTime) - Number(a.startTime)
        })
        globalThis.reportPerformance = data
    })
 }

 export async function refreshReportListDb(): Promise<Array<ReportItem>> {
    return getReportListDb().then(res => {
        globalThis.reportList = res
        let resReport: Array<ReportItem> = res
        globalThis.sumTest = resReport.length
        globalThis.sumTestTime = 0
        let sumTestAppMap = new Map
        for (let item of resReport) {
            sumTestAppMap.set(item.appName, "")
            globalThis.sumTestTime += Number(item.testDuration).valueOf()
        }
        globalThis.sumTestApp = sumTestAppMap.size
        return globalThis.reportList
    }).catch (err => {

    })
 }

export async function getReportListDb(): Promise<Array<ReportItem>> {
  var result = Array<ReportItem>()
  await database.queryGeneralData().then(generals => {
    for (var i = 0; i < generals.length; i++) {
      var curGeneralInfo = generals[i]
      result.push(
        new ReportItem(
          curGeneralInfo.sessionId.toString(),
          curGeneralInfo.taskId.toString(),
          AppFileRealDir + curGeneralInfo.sessionId.toString(),
          curGeneralInfo.packageName,
          "",
          curGeneralInfo.taskName,
          curGeneralInfo.appName,
          dateFormat(curGeneralInfo.startTime),
          curGeneralInfo.testDuration.toString(),
          curGeneralInfo.upStatus,
          curGeneralInfo.projectId,
          curGeneralInfo.syncStatus
        ))
    }
  })
  return result
}

export async function updateUploadStatus(sessionId: String) {
    await database.changeUploadStatus(sessionId)
    let reportItems:ReportItem[]=globalThis.reportList
    reportItems.forEach(v=>{
      if (v.sessionId==sessionId) {
        v.upStatus='1'
      }
    })
    CommonEvent.publish("updata.report", {code:0, data:"update report msg",}, (err) => {
    })
}
export async function updateSyncStatus(sessionIds?:string[]) {
  await database.updateSyncStatus(sessionIds)
  CommonEvent.publish("updata.report", {code:0, data:"update report msg",}, (err) => {
  })
}
export async function refreshReportFPSDb() {
    database.queryFrameRateInfo().then(data => {
        data.sort(function (a,b) {
            return Number(b.startTime) - Number(a.startTime)
        })
        globalThis.reportFPSData = data
    })
}
